<template>
    <view class="container">
        <view class="order_list" v-if="orderList&&orderList.length!=0">
            <view class="order_item" v-for="(item,index) in orderList" :key="index" @click="selectItemFun(item.id)">
              <view class="order_item_state" :style="{background:item.state?defaultColor:'',border:'2rpx solid '+(item.state?defaultColor:'#ccc')}">
                  <image class="order_item_state_icon" src="https://image1.sansancloud.com/xianhua/2020_6/8/16/35/40_25.jpg?x-oss-process=style/preview_120"></image>
              </view>
              <view class="item_info">
                  <view class="item_info_left">
                      <view class="item_info_options">
                          <image class="item_info_options_icon" src="https://image1.sansancloud.com/xianhua/2020_6/8/17/18/1_861.jpg?x-oss-process=style/preview_120"></image>
                          <text class="item_info_options_text">{{item.orderNo}}</text>
                      </view>
                      <view class="item_info_options">
                          <image class="item_info_options_icon" src="https://image1.sansancloud.com/xianhua/2020_6/8/18/3/10_466.jpg?x-oss-process=style/preview_120"></image>
                          <text class="item_info_options_text">{{item.perTime}} {{item.weekOne}} {{item.endTime}}</text>
                      </view>
                  </view>
                  <view class="item_info_right">
                      <view class="item_price_block">
                          <text class="item_price" :style="{color: defaultColor}">
                              {{item.endPrice}}
                          </text>
                          <text class="item_price_unit">元</text>
                      </view>
                  </view>
              </view>
            </view>
        </view>
        <view class="noproduct" v-else>
          <image mode="widthFix" src='https://image1.sansancloud.com/xianhua/2019_12/16/15/54/55_950.jpg?x-oss-process=style/preview_120'></image>
          <text>没有可开票的订单</text>
        </view>
        <view class="bottom_block">
            <view class="bottom_block_top">
                <text :style="{color:defaultColor,marginRight:'10rpx'}">{{selectList.length}}</text> 个订单，共 <text :style="{color:defaultColor,margin:'0 10rpx'}">{{allPrice}}</text> 元
            </view>
            <view class="fun_list">
                <view class="fun_list_left">
                    <view class="fun_left_item" @click="selectCurAllOrderFun()">
                        <view class="order_item_state" :style="{background:(allSelectState?defaultColor:''),border:'2rpx solid '+(allSelectState?defaultColor:'#ccc')}">
                            <image class="order_item_state_icon" src="https://image1.sansancloud.com/xianhua/2020_6/8/16/35/40_25.jpg?x-oss-process=style/preview_120"></image>
                        </view>
                        <text class="fun_left_item_text">本页全选</text>
                    </view>
                </view>
                <view class="fun_list_right">
                    <!-- <text class="fun_list_right_text" v-if="selectList.length!=0" :style="{background:selectList.length!=0?defaultColor:'#ccc'}">下一步</text> -->
                    <text class="fun_list_right_text" v-if="selectList.length!=0" :style="{background:defaultColor}" @click="nextStepFun()">下一步</text>
                    <text class="fun_list_right_text" v-else style="background:#ccc">下一步</text>
                </view>
            </view>
        </view>
       <!-- 填写表单弹窗动画 -->
       <view class='zhezhao' v-if="showAttendForm" @tap='closeZhezhao'></view>
       <view class='popupFormDetail' :animation="animationData">
         <view class='form_title' >
           <text ></text>
           <text>请填写以下信息</text>
           <image class='close_popup_icon' src='https://image1.sansancloud.com/xianhua/2019_7/31/15/25/40_755.jpg?x-oss-process=style/preview_120' @click='closeZhezhao'></image>
         </view>
         <scroll-view scroll-y  style='max-height:700rpx'>
           <view v-if="sendOptionData&&showAttendForm">
              <form-detail-component id="submitOrderForm" :receiveData="sendOptionData" :showTitle="false" :showBtn="false" @sendDataFun="getDataFun"></form-detail-component><!-- 弹窗-->
           </view>
           </scroll-view>
       </view>
       <view v-if="sendOptionData&&showAttendForm" class='submitBtn' :style='{background:assistanceDetail.buttonColor||defaultColor}' @click='submitData'>
         <text>提交</text>
       </view>
    </view>
</template>

<script>
import { socketFun } from "../../wxcomponents/public/json2Form";
export default {
  data() {
    return {
      orderList:null,
      setting:null,
      listPage:{
          page: 1,
          pageSize: 20,
          totalSize: 0,
      },
      secondColor:'',
      defaultColor:'',
      options:'',
      checkedState:false,
      selectList:[],
      allPrice:'0.00',
      allSelectState:false,
      showAttendForm:false,
      animationData:null,
      sendOptionData:null,
    };
  },
  props: {},

  /*onload*/
  onLoad: function (options) {
    let that=this;
    console.log("======onLoad:options======", options, getApp().globalData.setting);
    setTimeout(function(){
        that.getData(that.listPage,'upload');
    },500)
  },
  onReady: function () {
    
  },
  onShow: function () {
    let that=this;
	that.setData({
        setting:getApp().globalData.setting,
        defaultColor:getApp().globalData.setting.platformSetting.defaultColor,
        secondColor:getApp().globalData.setting.platformSetting.secondColor,
       })
  },
  /* 分享 app.js862行*/
  onShareAppMessage: function () {
    console.log(getApp().globalData.miniIndexPage);
    return getApp().globalData.shareForFx2(getApp().globalData.miniIndexPage);
  },
  onPullDownRefresh: function () {
    let that = this; 
    console.log("下拉");
    that.listPage.page=1
    that.getData(that.listPage);
    wx.stopPullDownRefresh();
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    console.log('===onReachBottom====');
    let that = this
    if (that.listPage.totalSize > that.listPage.page * that.listPage.pageSize) {
      that.listPage.page++
      that.getData(that.listPage);
    }else{
        wx.showToast({
          title: "到底了~",
          image: '/wxcomponents/images/icons/tip.png',
          duration: 1000
        });
    }
  },
  methods: {
    selectCurAllOrderFun:function(){
        console.log("====selectCurAllOrderFun====")
        let that=this;
        let selectList=[];
        let orderList=that.orderList;
        let perState=that.allSelectState;
        if(perState){
            that.judgeAllStateFun(that.selectList,orderList,perState)
            return
        }
        for(let i=0;i<that.orderList.length;i++){
            if(!that.orderList[i].state){
                that.$set(that.orderList[i],'state',true);
            }
            selectList.push(that.orderList[i].id);
        }
        console.log("===selectList===",selectList,selectList.length,that.orderList.length);
        that.selectList=selectList;
        that.imputedPriceFun();
        that.judgeAllStateFun(selectList,orderList,perState)
    },
    imputedPriceFun:function(){
        console.log("==imputedPriceFun===",);
        let that=this;
        let allPrice=0;
        for(let i=0;i<that.orderList.length;i++){
            if(that.orderList[i].state){
                allPrice+=Number(that.orderList[i].endPrice)
            }
        }
        console.log("==allPrice===",allPrice)
        that.allPrice=allPrice.toFixed(2)
    },
    judgeAllStateFun:function(selectList,orderList,perState){
        let that=this;
        console.log("===perState===",perState)
        if(perState&&perState!='more'){
            console.log("===perState===",perState)
            that.selectList=[];
            that.allSelectState=false;
            that.allPrice='0.00'
            for(let i=0;i<that.orderList.length;i++){
                that.$set(that.orderList[i],'state',false);
            }
            console.log("===selectList===",that.selectList,that.selectList.length,that.orderList.length);
        }else{
            if(selectList.length==orderList.length&&selectList.length!=0){
                that.allSelectState=true;
            }else{
                that.allSelectState=false
            }
        }
    },
    selectItemFun: function (id) {
      console.log('====selectItemFun====',id);
      let that=this;
      let selectList=that.selectList;
      for(let i=0;i<that.orderList.length;i++){
          if(that.orderList[i].id==id){
              if(that.orderList[i].state){
                  that.$set(that.orderList[i],'state',false);
                  for(let j=0;j<selectList.length;j++){
                      if(selectList[j]==that.orderList[i].id){
                          console.log("===删除===",selectList[j],id)
                          selectList.splice(j,1);
                      }
                  }
              }else{
                  that.$set(that.orderList[i],'state',true);
                  selectList.push(that.orderList[i].id);
                  console.log("===增加===",selectList,id)
              }
          }
      }
      that.selectList=selectList
      that.imputedPriceFun();
      that.judgeAllStateFun(selectList,that.orderList)
      console.log("===orderList===",that.orderList)
    },
    nextStepFun:function(){
        let that=this;
        console.log("===nextStepFun===",that.setting);
        let invoiceAble=that.setting.platformSetting.invoiceAble
        let invoiceCustomFormId=that.setting.platformSetting.invoiceCustomFormId;
        console.log("===invoiceCustomFormId===",invoiceAble,invoiceCustomFormId)
        if(invoiceAble==1&&invoiceCustomFormId){
            console.log("===invoiceCustomFormId===",)
            let showAttendForm=!that.showAttendForm;
            that.setData({
              sendOptionData: { customFormId: invoiceCustomFormId },
              showAttendForm: showAttendForm,
            })
            let animation = wx.createAnimation({
              duration: 400,
              timingFunction: 'ease',
            })
            console.log("showAttendForm",showAttendForm,that.sendOptionData)
            if (showAttendForm) {
              animation.bottom('100rpx').step()
            } else {
              animation.bottom('-200rpx').step()
            }
            that.setData({
              animationData: animation.export(),
            })
        }else{
            wx.showToast({
              title: "开票失败！",
              image: '/wxcomponents/images/icons/tip.png',
              duration: 1000
            });
        }
    },
    submitData:function(){
        let that=this;
        that.selectComponent("#submitOrderForm").formSubmit();
    },
    getDataFun: function (e) {
      let that = this;
      console.log("===getDataFun===", e, e.detail.formId)
      that.submitInvoiceFun(e.detail.formId)
    },
    submitInvoiceFun:function(formId){
      console.log("===submitInvoiceFun===",formId)
      let that = this;
      let orderIds=that.selectList.join(',')
      let params={
          customFormId:that.sendOptionData.customFormId,
          commitId:formId||0,
          orderIds:orderIds,
      }
      console.log("===params==",params)
      var customIndex = getApp().globalData.AddClientUrl("/wx_request_order_invoice.html", params)
      getApp().globalData.showToastLoading('loading', true)
      wx.request({
        url: customIndex.url,
        header: getApp().globalData.header,
        success: function (res) {
          wx.hideLoading()
          console.log(res.data)
          that.closeZhezhao()
          let data=res.data.relateObj;
          if(res.data.errcode==0){
              wx.showToast({
                title: "开票成功",
                icon:'success',
                duration: 1000
              });
              setTimeout(function(){
                that.listPage.page=1
                that.getData(that.listPage,'upload')
              },1000)
          }else{
              wx.showToast({
                title: res.data.errMsg,
                image: '/wxcomponents/images/icons/tip.png',
                duration: 1000
              });
          }
          wx.hideLoading()
        },
        fail: function (res) {
          console.log("fail")
          wx.hideLoading()
          getApp().globalData.loadFail()
        }
      })
        
    },
    closeZhezhao:function(){
      console.log("======closeZhezhao=========")
      let that=this;
      that.setData({ showAttendForm: false })
      let animation = wx.createAnimation({
        duration: 400,
        timingFunction: 'ease',
      })
      animation.bottom('-200rpx').step()
      let setData = animation.export()
      that.setData({
        animationData: setData,
      })
    },
    /* 获取数据 */
    getData: function (param,state) {
      var that = this
      console.log("===param==",param)
      var customIndex = getApp().globalData.AddClientUrl("/wx_find_uninvoice_orders.html", param)
      getApp().globalData.showToastLoading('loading', true)
      wx.request({
        url: customIndex.url,
        header: getApp().globalData.header,
        success: function (res) {
          wx.hideLoading()
          console.log(res.data)
          let data=res.data.relateObj.result
          that.listPage.pageSize = res.data.relateObj.pageSize
          that.listPage.page = res.data.relateObj.curPage
          that.listPage.totalSize = res.data.relateObj.totalSize
          let dataArr = that.orderList;
          for (let i = 0; i < data.length; i++) {
            that.$set(data[i],'state',false);
            data[i].endPrice=(data[i].totalPayedAmount-data[i].backAmount).toFixed(2)
            if(data[i].addTime){
              let addTime=data[i].addTime.replace(/\-/g, "/"); 
              data[i].perTime=data[i].addTime.replace(/\-/g, ".").slice(0,10);
              data[i].endTime=data[i].addTime.slice(11,-3);
              let dateTime = new Date(addTime);
              let dayNum=dateTime.getDay();
              switch (dayNum) {
                case 0:
                    data[i].weekOne='周日'
                  break;
                case 1:
                    data[i].weekOne='周一'
                  break;
                case 2:
                    data[i].weekOne='周二'
                  break;
                case 3:
                    data[i].weekOne='周三'
                  break;
                case 4:
                    data[i].weekOne='周四'
                  break;
                case 5:
                    data[i].weekOne='周五'
                  break;
                case 6:
                    data[i].weekOne='周六'
                  break;
              }
            }
          }
          console.log("===data====",data)
          if (param.page == 1) {
            dataArr = []
          }
          if (!data || data.length == 0) {
            that.setData({ orderList: [] })
          } else {
            dataArr = dataArr.concat(data)
            that.setData({ orderList: dataArr })
          }
          if(state=='upload'){
              that.selectList=[];
              that.allPrice='0.00'
          }
          that.judgeAllStateFun(that.selectList,dataArr,'more')
          wx.hideLoading()
        },
        fail: function (res) {
          console.log("fail")
          wx.hideLoading()
          getApp().globalData.loadFail()
        }
      })
    },
    /* 组件事件集合 */
    tolinkUrl: function (e) {
      console.warn("=======e=======", e);
      let linkUrl = e.currentTarget.dataset.url;
      getApp().globalData.linkEvent(linkUrl);
    },
    setData: function (obj) {
      let that = this;
      let keys = [];
      let val, data;
      Object.keys(obj).forEach(function (key) {
        keys = key.split('.');
        val = obj[key];
        data = that.$data;
        keys.forEach(function (key2, index) {
          if (index + 1 == keys.length) {
            that.$set(data, key2, val);
          } else {
            if (!data[key2]) {
              that.$set(data, key2, {});
            }
          }

          data = data[key2];
        });
      });
    }
  }
};
</script>
<style>
@import "./index.css";
</style>